package cn.enjoy.tool.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.*;

public class CollectionUtil extends CollectionUtils {

    public static <T> boolean contains(@Nullable T[] array, final T element) {
        if (array == null) {
            return false;
        }
        return Arrays.stream(array).anyMatch(x -> ObjectUtil.nullSafeEquals(x, element));
    }

    /**
     * 通过key分组，用于返回echars报表数据格式
     * @param list
     */
    public static void groupByKey(List list) {
        String jsonString = JSONObject.toJSONString(list);

        try {
            // fastjson
            JSONArray jsonArray = JSON.parseArray(jsonString);
            Map<String, List<Object>> groupedResult = new HashMap<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                for (String key : jsonObject.keySet()) {
                    if (!groupedResult.containsKey(key)) {
                        groupedResult.put(key, new ArrayList<>());
                    }
                    groupedResult.get(key).add(jsonObject.get(key));
                }
            }
            System.out.println(JSON.toJSONString(groupedResult, true));

            // jackson
            ObjectMapper objectMapper = new ObjectMapper();

            Map<String, List<Object>> groupedMap = new HashMap<>();
            JsonNode rootNode = objectMapper.readTree(jsonString);
            for (JsonNode node : rootNode) {
                Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    String key = entry.getKey();
                    Object value = entry.getValue().asText();

                    if (!groupedMap.containsKey(key)) {
                        groupedMap.put(key, new ArrayList<>());
                    }

                    groupedMap.get(key).add(value);
                }
            }
            for (Map.Entry<String, List<Object>> entry : groupedMap.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
